<template>
  <div
    ref="dialogRef"
    id="request-interceptor-dialog"
    @mousedown="handleHeaderMouseDown"
  >
    <div class="dialog-header" ref="headerRef">
      <div class="dialog-title">
        <span class="title-icon">🔧</span>
        <span class="title-text">Request Interceptor</span>
      </div>
      <div class="dialog-controls">
        <button class="control-btn minimize-btn" title="最小化" @click="$emit('close')">−</button>
        <button class="control-btn maximize-btn" title="最大化" @click="toggleMaximize">□</button>
        <button class="control-btn close-btn" title="关闭" @click="$emit('close')">×</button>
      </div>
    </div>

    <div class="dialog-content">
      <div class="tabs-container">
        <div class="tab-buttons">
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'requests' }"
            @click="activeTab = 'requests'"
          >
            <span class="tab-icon">📡</span>
            <span class="tab-text">网络请求</span>
            <span class="tab-count">{{ store.getFilteredRequests().length }}</span>
          </button>
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'intercepted' }"
            @click="activeTab = 'intercepted'"
          >
            <span class="tab-icon">🎯</span>
            <span class="tab-text">已拦截</span>
            <span class="tab-count">{{ store.getFilteredIntercepted().length }}</span>
          </button>
        </div>

        <!-- 网络请求标签页 -->
        <div v-show="activeTab === 'requests'" class="tab-content">
          <div class="toolbar">
            <div class="toolbar-left">
              <el-button size="small" @click="clearRequests">清空列表</el-button>
            </div>
            <div class="toolbar-right">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索请求..."
                size="small"
                style="width: 180px"
                clearable
              />
            </div>
          </div>
          <div class="content-area">
            <RequestsList @open-editor="handleOpenEditor" />
          </div>
        </div>

        <!-- 已拦截标签页 -->
        <div v-show="activeTab === 'intercepted'" class="tab-content">
          <div class="toolbar">
            <div class="toolbar-left">
              <el-switch
                v-model="batchDisableEnabled"
                @change="toggleBatchDisable"
                active-text="批量禁用"
                size="small"
              />
              <el-button size="small" @click="clearInterceptedRequests" type="danger">
                清空拦截
              </el-button>
            </div>
            <div class="toolbar-right">
              <el-input
                v-model="interceptedSearchKeyword"
                placeholder="搜索拦截规则..."
                size="small"
                style="width: 180px"
                clearable
              />
            </div>
          </div>
          <div class="content-area">
            <InterceptedList @edit="handleEdit" />
          </div>
        </div>
      </div>
    </div>

    <div class="resize-handle" @mousedown="handleResizeMouseDown"></div>
  </div>


</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useInterceptorStore } from '@/stores/interceptor'
import { ElMessage, ElMessageBox } from 'element-plus'
import RequestsList from './RequestsList.vue'
import InterceptedList from './InterceptedList.vue'

const emit = defineEmits(['close', 'open-editor'])

const store = useInterceptorStore()
const activeTab = ref('requests')

// 添加缺失的ref定义
const dialogRef = ref(null)
const headerRef = ref(null)
const isMaximized = ref(false)

// 从store获取响应式数据
const {
  searchKeyword,
  interceptedSearchKeyword,
  batchDisableEnabled
} = storeToRefs(store)

// 拖拽功能
let isDragging = false
let isResizing = false
let startX, startY, startLeft, startTop, startWidth, startHeight

const handleHeaderMouseDown = (e) => {
  // 忽略控制按钮的点击
  if (e.target.classList.contains('control-btn') || e.target.closest('.control-btn')) {
    return
  }

  isDragging = true
  startX = e.clientX
  startY = e.clientY

  const rect = dialogRef.value.getBoundingClientRect()
  startLeft = rect.left
  startTop = rect.top

  headerRef.value.style.cursor = 'grabbing'
  dialogRef.value.style.userSelect = 'none'
  // 不在body上设置userSelect，避免影响输入框

  e.preventDefault()
  e.stopPropagation()
}

const handleMouseMove = (e) => {
  if (isDragging) {
    const deltaX = e.clientX - startX
    const deltaY = e.clientY - startY

    const newLeft = startLeft + deltaX
    const newTop = startTop + deltaY

    // 限制在视窗内
    const maxLeft = window.innerWidth - dialogRef.value.offsetWidth
    const maxTop = window.innerHeight - dialogRef.value.offsetHeight

    const finalLeft = Math.max(0, Math.min(newLeft, maxLeft))
    const finalTop = Math.max(0, Math.min(newTop, maxTop))

    dialogRef.value.style.left = finalLeft + 'px'
    dialogRef.value.style.top = finalTop + 'px'
    dialogRef.value.style.right = 'auto'
    dialogRef.value.style.bottom = 'auto'
  }

  if (isResizing) {
    const newWidth = startWidth + (e.clientX - startX)
    const newHeight = startHeight + (e.clientY - startY)

    const minWidth = 400
    const minHeight = 300

    dialogRef.value.style.width = Math.max(minWidth, newWidth) + 'px'
    dialogRef.value.style.height = Math.max(minHeight, newHeight) + 'px'
  }
}

const handleMouseUp = () => {
  if (isDragging) {
    isDragging = false
    headerRef.value.style.cursor = 'move'
    dialogRef.value.style.userSelect = ''
    // 不需要恢复body的userSelect，因为我们没有设置它
  }

  isResizing = false
}

const handleResizeMouseDown = (e) => {
  isResizing = true
  startX = e.clientX
  startY = e.clientY
  startWidth = parseInt(window.getComputedStyle(dialogRef.value).width, 10)
  startHeight = parseInt(window.getComputedStyle(dialogRef.value).height, 10)
  e.preventDefault()
}

const toggleMaximize = () => {
  if (isMaximized.value) {
    isMaximized.value = false
    dialogRef.value.style.width = '500px'
    dialogRef.value.style.height = '600px'
    dialogRef.value.style.top = '50px'
    dialogRef.value.style.right = '50px'
    dialogRef.value.style.left = 'auto'
    dialogRef.value.style.bottom = 'auto'
  } else {
    isMaximized.value = true
    dialogRef.value.style.width = '100vw'
    dialogRef.value.style.height = '100vh'
    dialogRef.value.style.top = '0'
    dialogRef.value.style.left = '0'
    dialogRef.value.style.right = 'auto'
    dialogRef.value.style.bottom = 'auto'
  }
}

const clearRequests = async () => {
  try {
    await store.clearRequests()
    ElMessage.success('请求列表已清空')
  } catch (error) {
    ElMessage.error('清空失败')
  }
}

const clearInterceptedRequests = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有拦截规则吗？此操作不可撤销。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await store.clearInterceptedRequests()
    ElMessage.success('拦截列表已清空')
  } catch {
    // 用户取消操作
  }
}

const toggleBatchDisable = () => {
  store.toggleBatchDisable(batchDisableEnabled.value)
  ElMessage.success(
    batchDisableEnabled.value ? '已批量禁用所有规则' : '已批量启用所有规则'
  )
}

// 编辑相关方法
const handleEdit = (item) => {
  // 发射事件给父组件处理，传递现有规则的数据
  emit('open-editor', {
    id: item.id,
    url: item.url,
    method: item.method,
    responseData: item.responseData,
    requestHeaders: item.editedParams?.requestHeaders || {},
    requestBody: item.editedParams?.requestBody || null
  })
}

const handleOpenEditor = (data) => {
  // 发射事件给父组件处理
  emit('open-editor', data)
}



onMounted(() => {
  // 绑定全局事件
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)

  // 初始化样式
  headerRef.value.style.cursor = 'move'
  headerRef.value.style.userSelect = 'none'

  // 加载数据
  store.loadData()
})

onUnmounted(() => {
  // 清理事件监听器
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
})
</script>

<style scoped>
/* 复制原来的样式 */
#request-interceptor-dialog {
  position: fixed;
  top: 50px;
  right: 50px;
  width: 500px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  min-width: 400px;
  min-height: 300px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  cursor: move;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  transition: background 0.2s ease;
}

.dialog-header:active {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.dialog-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
}

.title-icon {
  font-size: 16px;
}

.dialog-controls {
  display: flex;
  gap: 4px;
}

.control-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: background 0.2s;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.close-btn:hover {
  background: #ff4757;
}

.dialog-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.tab-buttons {
  display: flex;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.tab-btn {
  flex: 1;
  padding: 12px 16px;
  border: none;
  background: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #6c757d;
  transition: all 0.2s;
  border-bottom: 2px solid transparent;
}

.tab-btn.active {
  color: #667eea;
  background: white;
  border-bottom-color: #667eea;
}

.tab-btn:hover:not(.active) {
  background: #e9ecef;
  color: #495057;
}

.tab-count {
  background: #6c757d;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  min-width: 18px;
  text-align: center;
}

.tab-btn.active .tab-count {
  background: #667eea;
}

.tab-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.toolbar-left, .toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.resize-handle {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 16px;
  height: 16px;
  cursor: nw-resize;
  background: linear-gradient(-45deg, transparent 0%, transparent 30%, #ccc 30%, #ccc 40%, transparent 40%, transparent 60%, #ccc 60%, #ccc 70%, transparent 70%);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  max-height: 400px;
  min-height: 200px;
}

.resize-handle {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  cursor: nw-resize;
  background: linear-gradient(-45deg, transparent 0%, transparent 40%, #ccc 40%, #ccc 60%, transparent 60%);
}

/* 确保输入框文本可以被选中 */
:deep(.el-input__inner) {
  user-select: text !important;
  -webkit-user-select: text !important;
  -moz-user-select: text !important;
  -ms-user-select: text !important;
  pointer-events: none!important;
}

:deep(.el-input__inner::selection) {
  background: #409eff !important;
  color: #ffffff !important;
}

:deep(.el-input__inner::-moz-selection) {
  background: #409eff !important;
  color: #ffffff !important;
}
</style>
